//
//  MBUserWatchInfoView.swift
//  Merchants
//
//  Created by kingly on 2020/7/21.
//  Copyright © 2020 VALUABLE JADE(SHENZHEN) JEWELRY JADE Co.,Ltd. All rights reserved.
//

import UIKit

class MBUserWatchInfoView: UIView {
 
     deinit {
       destroytime()
       print("deinit:: MBUserWatchInfoView")
       
     }
    var liveNum : Int32 = 0
    var livetime : String = "00:00:00"
    var WachNumber : Int32 = 1000000
    
     fileprivate var timer    : GCDTimer!
    
     override init(frame: CGRect) {
          super.init(frame: frame)
          
          setupCustomView()
          setuplayout()
      }
      
      required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
      }
      
      
    private func setupCustomView() {
       
        self.isUserInteractionEnabled = true
    

        self.addSubview(UserWatchInfoLabel)
    }
    // MARK: - layout
    private func setuplayout() {
        
        self.UserWatchInfoLabel.layer.masksToBounds = true
        self.UserWatchInfoLabel.layer.cornerRadius  = 16
        
       
            
    }
    
    
   fileprivate lazy var UserWatchInfoLabel  : UILabel = {
           var titleLabel = UILabel()
           titleLabel.backgroundColor = UIColor(hexStr: "000000", alpha: 1)
           titleLabel.font = UIFont.systemFont(ofSize: 12)
           titleLabel.textColor = .white
           titleLabel.textAlignment = .center
           titleLabel.text =  "\(WachNumber) 在看 / 直播时长 " + livetime
           return titleLabel
    }()
    
    /// 设置观看人数
    func setupWachNumber(Num: Int32) {
        
         WachNumber = Num
        
        if (Num == 0) {
            liveNum = 1
            
            if(timer != nil){
                timer.destroy()
                timer = nil
            }
            weak var weakSelf = self
            timer = GCDTimer(in: GCDQueue.Main, delay: 0.0, interval: 0.1)
            timer.setTimerEventHandler { _ in
                weakSelf?.setuplivetime()
            }
            timer.start()
        }
    
        let UserWatchInfoStr: String = "\(WachNumber) 在看 / 直播时长 " + livetime
        
        UserWatchInfoLabel.text = UserWatchInfoStr
        
        let UserWatchInfowidth  = UserWatchInfoStr.getWidth(fontSize: 12.0, height: 32.0)
       
        UserWatchInfoLabel.frame = CGRect(x: 0, y: 0, width: UserWatchInfowidth + 32 , height: 32)
    
        UserWatchInfoLabel.textAlignment = .center
    
    }
}

extension MBUserWatchInfoView {
   
    func setuplivetime() {
        liveNum += 1
        livetime = String().ky_transToHourMinSec(time:Float(liveNum))
        let UserWatchInfoStr: String = "\(WachNumber) 在看 / 直播时长 " + livetime
        UserWatchInfoLabel.text = UserWatchInfoStr
    }
     
    func destroytime(){
         if(timer != nil){
             timer.destroy()
             timer = nil
         }
    }
    
}



